//
//  SearchView.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/16.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

import UIKit

class SearchView: UIView {
    
    @IBOutlet weak var trailing: NSLayoutConstraint!
    @IBOutlet weak var cancleButton: UIButton!
    @IBOutlet weak var textbbaj: UITextField!
    
    override func awakeFromNib() {
        
        //要更改文本框左边的 leftView , 必须改写以下2个条件
        textbbaj.leftView = leftView
        textbbaj.leftViewMode = .Always
        
        //修改图片框的大小(等于输入框的高度)
        leftView.frame.size = CGSize(width: self.bounds.height, height: self.bounds.height)
    }
    
    // MARK: - 懒加载leftView
    lazy var leftView:UIImageView = {
        
        let imgView = UIImageView()
        
        //设置 leftView 的图片
        imgView.image = UIImage(named: "searchbar_textfield_search_icon")
        
        /*
        case ScaleToFill --> 控件多大，里面的内容就多大 （不会按等比例拉伸，显示出来的图片可以会很难看）
        case ScaleAspectFit --> 控件里面的内容会全部显示在控件之内 (会按比例)
        case ScaleAspectFill --> 会按比例拉伸至填充整个控件（会按比例）
        case Redraw // redraw on bounds change (calls -setNeedsDisplay)
        case Center // contents remain same size. positioned adjusted.
        case Top
        case Bottom
        case Left
        case Right
        case TopLeft
        case TopRight
        case BottomLeft
        case BottomRight
        */
        //设置image 的 contentMode ,此属性不会随图片框的大小改变而改变,它会保持原来大小
        imgView.contentMode = .Center
        
        //设置图片框的大小
//        imgView.sizeToFit()
        
        return imgView
    }()
    
    //定义一个类方法
    class func searchView() -> SearchView {
        return NSBundle.mainBundle().loadNibNamed("SearchView", owner: nil, options: nil).last as! SearchView
    }
    
    // MARK: - 点击了输入框
    @IBAction func editingDidBegin(sender: UITextField) {
        
        print("editingDidBegin")
        trailing.constant = self.cancleButton.bounds.width
        
        //约束执行动画,必须在动画里调用 layoutIfNeeded
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.layoutIfNeeded()
            
            //You should not call this method directly. If you want to force a layout update, call the setNeedsLayout method instead to do so prior to the next drawing update. If you want to update the layout of your views immediately, call the layoutIfNeeded method.
//            self.layoutSubviews()
        }
    }
    
    // MARK: - 点击了取消按钮
    @IBAction func didClickCancelButton(sender: UIButton) {
        
        print("didClickCancelButton")
        
        //约束改为原始
        trailing.constant = 0
        
        //约束执行动画
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.layoutIfNeeded()
        }
        
        //辞去第一响应者
        textbbaj.resignFirstResponder()
    }
}
